{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "89237f36-b7dd-4951-b412-4a4ea20b9709",
   "metadata": {},
   "source": [
    "### 0.导入库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "aab006fe-8070-481a-9601-c9740281b331",
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "from deap import base\n",
    "from deap import creator\n",
    "from deap import tools\n",
    "from deap import algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16535c27-f475-45c2-9e46-8e98de24ef87",
   "metadata": {},
   "source": [
    "### 1. 创建问题类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "76623f8d-df08-4e9a-af86-64dd4c2c8bbf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 最大化目标函数 单变量，求最大值\n",
    "creator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))  \n",
    "# 创建Individual类，继承list\n",
    "creator.create(\"Individual\", list, fitness=creator.FitnessMax) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7cb00f9-4907-47e4-b026-2938dc053270",
   "metadata": {},
   "source": [
    "### 2. 初始化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a84b1f9c-d55a-4dde-b47c-90ce6193a75b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 初始化工具箱\n",
    "toolbox = base.Toolbox()\n",
    "\n",
    "# 定义基因生成器\n",
    "toolbox.register(\"attr_bool\", random.randint, 0, 1)\n",
    "\n",
    "# 定义个体生成器（长度为30的二进制列表）\n",
    "toolbox.register(\"individual\", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=30)\n",
    "\n",
    "# 定义种群生成器\n",
    "toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b90cfdd1-8488-487d-b5d7-22208f7e6daf",
   "metadata": {},
   "source": [
    "### 3. 定义算子"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "48d3428b-b91c-4cfa-b1b0-fadedec0716b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义评估函数（计算二进制列表的和）\n",
    "def evalOneMax(individual):\n",
    "    return sum(individual),\n",
    "\n",
    "toolbox.register(\"evaluate\", evalOneMax)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5497479e-1216-4b20-a057-382786663e1e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 注册选择、交叉和变异操作\n",
    "toolbox.register(\"select\", tools.selTournament, tournsize=3)\n",
    "toolbox.register(\"mate\", tools.cxTwoPoint)\n",
    "toolbox.register(\"mutate\", tools.mutFlipBit, indpb=0.05)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5226148e-c487-4846-9e54-a3c583902b97",
   "metadata": {},
   "source": [
    "### 4. 算法主流程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "4de2cf7a-8232-4edf-bc9d-7f6ead0cfe49",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 固定随机种子以确保结果可重复\n",
    "random.seed(42)  \n",
    "\n",
    "# 创建初始种群\n",
    "population = toolbox.population(n=50)\n",
    "\n",
    "# 遗传算法参数\n",
    "NGEN = 40  # 进化代数\n",
    "CXPB = 0.7  # 交叉概率\n",
    "MUTPB = 0.2  # 变异概率\n",
    "\n",
    "# 开始进化过程\n",
    "for gen in range(NGEN):\n",
    "    offspring = algorithms.varAnd(population, toolbox, cxpb=CXPB, mutpb=MUTPB)\n",
    "    fits = toolbox.map(toolbox.evaluate, offspring)\n",
    "    for fit, ind in zip(fits, offspring):\n",
    "        ind.fitness.values = fit\n",
    "    population = toolbox.select(offspring, k=len(population))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05d8ef29-41af-4319-9ddd-fd4ba029cd9c",
   "metadata": {},
   "source": [
    "### 5. 输出结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "d450335b-05dc-4069-8719-17cc730fe794",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Best individual: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n",
      "Fitness: 30.0\n"
     ]
    }
   ],
   "source": [
    "# 输出最佳个体\n",
    "top_individual = tools.selBest(population, k=1)[0]\n",
    "\n",
    "print(f\"Best individual: {top_individual}\")\n",
    "print(f\"Fitness: {top_individual.fitness.values[0]}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
